import sys
import os
import json
import urllib.request
from pprint import pprint
import datetime
from datetime import timedelta
import mysql.connector
import csv
import codecs

import MyLogger
import MyLib

#Déclaration
arguments = dict() #dict
i = 0 #Int
config_json = {} #Json
statusSupervision = "OK"

#####################################################################
#Les definitions

#Procedure
def lunch() :
    global config_json, statusSupervision, array_tag
    try:
        MyLogger.logger.debug("Début lunch")
        
        #Purge apache
        MyLogger.logger.info("Purge Apache")
        statutPurgeFichier = "OK"
        nbPurgeFichier = 0
        for objs in config_json["fichiers"]:
            nbPurgeFichier += 1
            try:
               with open(objs):
                    MyLogger.logger.debug("Suppression du fichier : "+objs)
                    os.remove(objs)
            except IOError:
                statutPurgeFichier = "WARNING"
                statusSupervision = "WARNING"
                MyLogger.logger.debug("Fichier non trouve : "+objs)

        #Connection
        cnx = mysql.connector.connect(host=config_json["config_user_maintenance"]["host"], user=config_json["config_user_maintenance"]["log"], password=config_json["config_user_maintenance"]["mdp"])
        cur = cnx.cursor(buffered=True)

        #Purge des tables des instances
        MyLogger.logger.info("Purge des tables trace/log/systeme des instances")
        statutPurgeTabTransaction = "OK"
        statutPurgeTabLog = "OK"
        nbInstance = 0
        for objs in config_json["instances"]:
            nbInstance += 1
            MyLogger.logger.debug("Purge de l'instance : "+objs["name"]+", table : "+objs["db"]+".API_TAB_TRANSACTION")
            sql = "DELETE FROM `"+objs["db"]+"`.`API_TAB_TRANSACTION` WHERE 1=1 AND `DEBUT` < (NOW() - INTERVAL 30 DAY);"
            try:
                cur.execute(sql)
                cnx.commit()
            except mysql.connector.Error as err:
                statusSupervision = "KO"
                statutPurgeTabTransaction = "KO"
                MyLogger.logger.error("Erreur : "+format(err))
                MyLogger.logger.debug("SQL : "+sql)

            MyLogger.logger.debug("Purge de l'instance : "+objs["name"]+", table : "+objs["db"]+".TAB_LOG")    
            sql = "DELETE FROM `"+objs["db"]+"`.`TAB_LOG` WHERE 1=1 AND `DATETIME` < (NOW() - INTERVAL 30 DAY);"
            try:
                cur.execute(sql)
                cnx.commit()
            except mysql.connector.Error as err:
                statusSupervision = "KO"
                statutPurgeTabLog = "KO"
                MyLogger.logger.error("Erreur : "+format(err))
                MyLogger.logger.debug("SQL : "+sql)

        #Purger Mysql
        MyLogger.logger.info("Purge du master MYSQL")
        statutPurgeCacheBase = "OK"
        sql = "RESET MASTER;"
        try:
            cur.execute(sql)
            cnx.commit()
        except mysql.connector.Error as err:
            statusSupervision = "KO"
            statutPurgeCacheBase = "KO"
            MyLogger.logger.error("Erreur : "+format(err))
            MyLogger.logger.debug("SQL : "+sql)

        #Fermeture connection    
        cnx.close()

        #supervision
        MyLogger.logger.info("Supervision")
        cnx_ring = mysql.connector.connect(user=config_json["config_db_supervision"]["db"], database=config_json["config_db_supervision"]["db"], password=config_json["config_db_supervision"]["mdp"], host=config_json["config_db_supervision"]["host"])
        cur_ring = cnx_ring.cursor(buffered=True)
        sql = "INSERT INTO `tab_log` (`id` ,`dateTime` ,`type` ,`commentaires`) VALUES (NULL , NOW(), 6, '[INFO][Statut:"+statusSupervision+"][Purge Apache, nbPurgeFichier:"+str(nbPurgeFichier)+", statutPurgeFichier:"+statutPurgeFichier+"][Purge tab, nbInstance:"+str(nbInstance)+", statutPurgeTabTransaction:"+statutPurgeTabTransaction+", statutPurgeTabLog:"+statutPurgeTabLog+"][Purge cache base, statutPurgeCacheBase:"+statutPurgeCacheBase+"]');"
        try:
            cur_ring.execute(sql)
            cnx_ring.commit()
        except mysql.connector.Error as err:
            MyLogger.logger.error("Erreur : "+format(err))
            MyLogger.logger.debug("SQL : "+sql)       
        cnx_ring.close()
        
        MyLogger.logger.debug("Fin lunch")
    except Exception as e:
        MyLogger.logger.error("Erreur pendant lunch : ("+format(e)+")")

#Procedure Say More
def more() :
    MyLogger.logger.info("Les options disponible sont : 'more','lunch'.")
    MyLogger.logger.info("Exemple de syntax pour 'lunch' : 'python ....maintenance\script_maintenance.py ....maintenance\exemple.config.maintenance.json lunch'.")
    MyLogger.logger.info("Exemple de syntax pour 'more' : '....maintenance\script_maintenance.py more'.")  

#####################################################################
#Le programme

#Message de bienvenu.
MyLogger.logger.info ("Bienvenue dans le script pour la maintenance du serveur ODA.")

#Récupération des arguments.
for x in sys.argv :
    i += 1
    if i == 2 :
        arguments["jsonFile"] = x
    elif i == 3 :
        arguments["action"] = x
        if x not in ["lunch","more"] :
            MyLogger.logger.warning("Votre premier argument ("+x+") est incorrect, seul 'more','read' sont aurorisés.")
            sys.exit("Erreur")
        else :
            MyLogger.logger.info("Mode d'action choisi : "+x+".")
            arguments["action"] = x
            
    if len(arguments) == 0 :
        arguments["action"] = "more"

#Initialisation
config_json = MyLib.charger_config(arguments["jsonFile"]) 

#Affichage        
if arguments["action"] == "lunch" :
    lunch()
elif arguments["action"] == "more" :
    more()

#Message de fin.
MyLogger.logger.info ("Fin du script.")
sys.exit(0)

    
